package com.topboya.linker.ui.activity;


import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.topboya.linker.R;
import com.topboya.linker.model.levelitem.SelectDeviceGroup;
import com.topboya.linker.model.levelitem.SelectVistorItem;
import com.topboya.linker.model.response.CustomerByOrgIdAndNewlyCusListResopnse;
import com.topboya.linker.model.response.CustomerByOrgIdResponse;
import com.topboya.linker.model.response.DictByKeyResponse;
import com.topboya.linker.model.response.NewlyOrgListResponse;
import com.topboya.linker.model.response.OrganizationResopnse;
import com.topboya.linker.ui.adapter.FlowdepTagAdapter;
import com.topboya.linker.ui.adapter.RecycleViewDivider;
import com.topboya.linker.ui.adapter.SeeVistorRightAdapter;
import com.topboya.linker.ui.adapter.SelecVistorLeftAdapter;
import com.topboya.linker.ui.adapter.SelecVistorRightAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.CustomerPresenter;
import com.topboya.linker.ui.view.CustomerView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SeeVistorActivity extends BaseActivity<CustomerView, CustomerPresenter> implements CustomerView {

    private static final String TAG = "SelectCustomerActivity:";
    private Toolbar toolbar;
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private Button btn_select;
//    private Button btn_selected;
//    private TextView tv_device_name;
//    private EditText et_add_new_device;
//    private TextView tv_add_new_department;
//    private TextView tv_add;
//    private LinearLayout ll_depart_empty;
//    private Button  btn_select;
    private SelectDeviceGroup docDetailInfo;
//    private TagFlowLayout id_flowlayout;
    private List<DictByKeyResponse.Data> data;
    private String orgID;
    private ArrayList<String> DepartnameList;
    private String departmentvalue;
    private List<String> listdepart;
    private FlowdepTagAdapter  flowdepTagAdapter;
    private ArrayList<String> selectepartnameList;
    private Set<Integer>  set;
    private List<SelectVistorItem> departmentListselected;
    private List<CustomerByOrgIdResponse.DepartmentList> departmentList;
    private List<List<SelectVistorItem>> departmentLists;
    private RecyclerView rl_visitor_right;
    private RecyclerView rl_visitor_letf;
    private List<String> departnameList;
    private SelecVistorLeftAdapter selecVistorLeftAdapter;
    private SeeVistorRightAdapter seeVistorRightAdapter;
    private boolean isCreateTask;
    private LinearLayout include_create_task_bottom;
    @Override
    protected int getLayoutId() {

        return R.layout.activity_see_visitor;

    }

    @Override
    protected void initView() {

        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        rl_visitor_right = findViewById(R.id.rl_visitor_right);
        rl_visitor_letf = findViewById(R.id.rl_visitor_letf);
//        btn_selected = findViewById(R.id.btn_selected);
//        btn_select = findViewById(R.id.btn_select);


//        tv_device_name = findViewById(R.id.tv_device_name);
//        tv_add_new_department = findViewById(R.id.tv_add_new_department);
//        tv_add = findViewById(R.id.tv_add);
//        ll_depart_empty = findViewById(R.id.ll_depart_empty);
//        btn_select = findViewById(R.id.btn_select);
//        id_flowlayout = findViewById(R.id.id_flowlayout);
//        et_add_new_device = findViewById(R.id.et_add_new_device);
        setRecycleView();
    }

    @Override
    protected void initData() {

        docDetailInfo = (SelectDeviceGroup) getIntent().getSerializableExtra("DocDetailInfo");
        isCreateTask = getIntent().getBooleanExtra("isCreateTask",true);
        LogUtils.v(TAG + "docDetailInfo:"+docDetailInfo.toString());
        toolbar_title.setText("客户列表");
        tv_toolbar_right.setText("新增");
        listdepart  = new ArrayList<>();
//        存放被选择的客户
        selectepartnameList = new ArrayList<>();

        seeVistorRightAdapter.SetisCreateTask(isCreateTask);
//        flowdepTagAdapter = new FlowdepTagAdapter(this,id_flowlayout,listdepart);
//        id_flowlayout.setAdapter(flowdepTagAdapter);

//        mPresenter.getCustomerByOrgId(docDetailInfo.getId(),null,false);
           mPresenter.getCustomerByOrgIdAndNewlyCusList(docDetailInfo.getId(),true);
//          mPresenter.getCustomerByOrgIdAndNewlyCusList("41458",true);
        // 根据字典查询科室，新增的时候用的上
//        mPresenter.getDictByKey("hos_department",null,null);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.v(TAG+"onNewIntent()");

        mPresenter.getCustomerByOrgIdAndNewlyCusList(docDetailInfo.getId(),true);

    }

    private void setRecycleView() {

        departmentLists = new ArrayList<>();
        departnameList = new ArrayList<>();
        RecyclerView.LayoutManager layoutManagerright = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rl_visitor_right.setLayoutManager(layoutManagerright);
        rl_visitor_right.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 1, 0xF5F7FA));
        seeVistorRightAdapter = new SeeVistorRightAdapter();
        rl_visitor_right.setAdapter(seeVistorRightAdapter);

        RecyclerView.LayoutManager layoutManagerleft = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rl_visitor_letf.setLayoutManager(layoutManagerleft);
//        rl_visitor_letf.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        selecVistorLeftAdapter = new SelecVistorLeftAdapter(departnameList);
        rl_visitor_letf.setAdapter(selecVistorLeftAdapter);


    }

    @Override
    protected void initListener() {
        toolbar.setNavigationOnClickListener(v -> {

            finish();
        });
        tv_toolbar_right.setOnClickListener(v -> {

           Intent intent = new Intent(SeeVistorActivity.this,AddCustomerActivity.class);
           intent.putExtra("docDetailInfo",docDetailInfo);
           startActivityForResult(intent,1001);

        });
//        tv_add_new_department.setOnClickListener(v -> {
//
//             if (null ==data){
//
//                 mPresenter.getDictByKey("hos_department",null,true);
//             }else {
//
//                 OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {
//
//                     String departname = DepartnameList.get(options1);
//                     LogUtils.v(TAG + "departname:"+departname);
//                     orgID =docDetailInfo.getId();
//                     departmentvalue = data.get(options1).getValue();
//                     tv_add_new_department.setText(departname);
//
//                 }).setCyclic(true,true,true)
//                         .setTextColorCenter(Color.BLUE)
//                         .build();
//                 pvOptions.setPicker(DepartnameList , null, null);
//                 pvOptions.show();
//
//             }
//
//        });
//        tv_add.setOnClickListener(v -> {
//
//           String  cusName = et_add_new_device.getText().toString().trim();
//
//           if (TextUtils.isEmpty(cusName) || TextUtils.isEmpty(orgID)){
//
//               UIUtils.showToast("请先填写完成信息");
//
//           }else {
//
//               mPresenter.createDoctorCustomer(orgID,cusName,null,departmentvalue,null);
//
//           }
//
//        });
//
//        id_flowlayout.setOnSelectListener(selectPosSet -> {
//
//            LogUtils.v("choose:" + selectPosSet.toString());
//            int size =selectPosSet.size();
//            btn_select.setText("选择（"+size+"）");
//            set =selectPosSet;
//
//            }
//        );
//        btn_select.setOnClickListener(v -> {
//
//            LogUtils.v(TAG +"set.toString():"+set.toString());
//            selectepartnameList.clear();
//            for (Integer select : set) {
//
//                selectepartnameList.add(listdepart.get(select));
//
//            }
//            Intent intent = new Intent(this,CreateTaskActivity1.class);
//            intent.putExtra("DocDetailInfo",docDetailInfo);
//            intent.putStringArrayListExtra("selectepartnameList",  selectepartnameList);
//            intent.putExtra("departmentList", (Serializable)departmentList);
//            startActivity(intent);
//
//        });
//        btn_selected.setOnClickListener(v -> {
//
//            //查看已选择的拜访对象
//            departmentListselected= seeVistorRightAdapter.getSelectDepartmentLists();
//            Intent intent = new Intent(SeeVistorActivity.this,SelectedDepartListActivity.class);
//            LogUtils.v(TAG + "departmentListselected："+departmentListselected.toString());
//            intent.putExtra("DocDetailInfo",docDetailInfo);
//            intent.putExtra("departmentListselected", (Serializable) departmentListselected);
//            startActivity(intent);
//
//        });
        selecVistorLeftAdapter.setOnItemClickListener((v, position) -> {

            selecVistorLeftAdapter.updateData(position);
            seeVistorRightAdapter.updateData(departmentLists,position);

        });
//        seeVistorRightAdapter.setOnitemChildCkickListener((view, position, count) -> {
//
//            btn_selected.setText("已选择："+count+"人");
//        });
        seeVistorRightAdapter.setOnItemClickListener((v, position,selectVistorItem) -> {

//            UIUtils.showToast("查看用户");
           Intent intent = new Intent(SeeVistorActivity.this,SeeSpecificActivity.class);
           intent.putExtra("selectVistorItem",selectVistorItem);
            intent.putExtra("docDetailInfo",docDetailInfo);

            startActivity(intent);


        });
//        btn_select.setOnClickListener(v -> {
//
//            departmentListselected= seeVistorRightAdapter.getSelectDepartmentLists();
//            LogUtils.v(TAG + "选中的拜访对象："+departmentListselected.toString());
//            Intent intent = new Intent(SeeVistorActivity.this,xCreateTaskActivity.class);
//            intent.putExtra("DocDetailInfo",docDetailInfo);
//            intent.putExtra("departmentListselected", (Serializable) departmentListselected);
//            startActivity(intent);
//
//
//        });
    }

    @Override
    protected CustomerPresenter createPresenter() {

        return new CustomerPresenter(this);
    }



    @Override
    public void setCustomeData(ArrayList<OrganizationResopnse.DocDetailInfoList> groupHList, ArrayList<NewlyOrgListResponse.Data> groupHListNewly) {


    }

    @Override
    public void setDepartment( List<CustomerByOrgIdResponse.DepartmentList> departmentlist) {

        this.departmentList = departmentlist;
        if (null == departmentlist){

//            id_flowlayout.setVisibility(View.GONE);
//            ll_depart_empty.setVisibility(View.VISIBLE);
        }else {

//            id_flowlayout.setVisibility(View.VISIBLE);
//            ll_depart_empty.setVisibility(View.GONE);
            listdepart.clear();
            for(int i=0; i <departmentlist.size(); i++){

                listdepart.add(departmentlist.get(i).getCusName());
                flowdepTagAdapter.notifyDataChanged();
            }
        }

    }

    @Override
    public void setDictByKey(List<DictByKeyResponse.Data> data) {

        this.data = data;
        DepartnameList = new ArrayList<>();
        for (int i =0;i<data.size();i ++){

            DepartnameList.add(data.get(i).getLabel()) ;
        }
    }

    @Override
    public void createCustomer() {

//        添加成功，刷新flowlayout
      mPresenter.getCustomerByOrgId(docDetailInfo.getId(),true);


    }

    @Override
    public void setDepartVisitor(HashMap<String, List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> departmentgroupmap,List<CustomerByOrgIdAndNewlyCusListResopnse.NewlyCusList> newlyCusLists) {

       // 得到制定医院下面获取科室对应的成员
        LogUtils.v(TAG+ "setDepartVisitor");
        departnameList.clear();
        departmentLists.clear();
        if (null !=newlyCusLists && newlyCusLists.size() >0){
            departnameList.add("最近");
            List<SelectVistorItem> selectVistorItemList = new ArrayList<>();
            for (CustomerByOrgIdAndNewlyCusListResopnse.NewlyCusList newlyCusList: newlyCusLists){
                SelectVistorItem selectVistorItem = new SelectVistorItem();
                selectVistorItem.setId(newlyCusList.getId());
                selectVistorItem.setCusName(newlyCusList.getCusName());
                selectVistorItemList.add(selectVistorItem);
            }
            departmentLists.add(selectVistorItemList);

        }
        for(Map.Entry<String,  List<CustomerByOrgIdAndNewlyCusListResopnse.CusListChild>> entry : departmentgroupmap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            departnameList.add(entry.getKey());
            List<SelectVistorItem> selectVistorItemList = new ArrayList<>();

            for (int i=0;i< entry.getValue().size();i++){

                SelectVistorItem selectVistorItem = new SelectVistorItem();
                selectVistorItem.setId(entry.getValue().get(i).getId());
                selectVistorItem.setCusName(entry.getValue().get(i).getCusName());
                selectVistorItemList.add(selectVistorItem);
            }
            departmentLists.add(selectVistorItemList);
        }
//        更新一下数据
        selecVistorLeftAdapter.updateData(0);
        for (int i=0;i < departmentLists.size();i++){

            LogUtils.v(TAG + "departmentLists:"+departmentLists.get(i).toString());
        }
        seeVistorRightAdapter.updateData(departmentLists,0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        LogUtils.v(TAG+"onActivityResult()");
        mPresenter.getCustomerByOrgIdAndNewlyCusList(docDetailInfo.getId(),true);


    }
}
